<script lang="ts" setup>
import type { VbenFormSchema } from '@vben/common-ui';
import type { Recordable } from '@vben/types';

import { computed, h, ref } from 'vue';
import { useRouter } from 'vue-router';

import { AuthenticationRegister, z } from '@vben/common-ui';
import { $t } from '@vben/locales';
import { ElNotification } from 'element-plus';

import { registerApi } from '#/api';

defineOptions({ name: 'Register' });

const loading = ref(false);
const router = useRouter();

const formSchema = computed((): VbenFormSchema[] => {
  return [
    {
      component: 'VbenInput',
      componentProps: {
        placeholder: '请输入用户名',
      },
      fieldName: 'username',
      label: '用户名',
      rules: z.string().min(1, { message: '请输入用户名' }),
    },
    {
      component: 'VbenInput',
      componentProps: {
        placeholder: '请输入手机号',
      },
      fieldName: 'phone',
      label: '手机号',
      rules: z.string().min(11, { message: '请输入正确的手机号' }),
    },
    {
      component: 'VbenInputPassword',
      componentProps: {
        passwordStrength: true,
        placeholder: '请输入密码',
      },
      fieldName: 'password',
      label: '密码',
      renderComponentContent() {
        return {
          strengthText: () => '密码强度',
        };
      },
      rules: z.string().min(6, { message: '密码至少6位' }),
    },
    {
      component: 'VbenInputPassword',
      componentProps: {
        placeholder: '请确认密码',
      },
      dependencies: {
        rules(values) {
          const { password } = values;
          return z
            .string({ required_error: '请确认密码' })
            .min(1, { message: '请确认密码' })
            .refine((value) => value === password, {
              message: '两次密码输入不一致',
            });
        },
        triggerFields: ['password'],
      },
      fieldName: 'confirmPassword',
      label: '确认密码',
    },
    {
      component: 'VbenCheckbox',
      fieldName: 'agreePolicy',
      renderComponentContent: () => ({
        default: () =>
          h('span', [
            '同意',
            h(
              'a',
              {
                class: 'vben-link ml-1 ',
                href: '',
              },
              '隐私政策 & 服务条款',
            ),
          ]),
      }),
      rules: z.boolean().refine((value) => !!value, {
        message: '请同意隐私政策和服务条款',
      }),
    },
  ];
});

async function handleSubmit(value: Recordable<any>) {
  try {
    loading.value = true;
    
    // 由于设置了 responseReturn: 'data'，成功的响应会直接返回 data 字段内容
    // 如果接口失败，会直接抛出错误进入 catch 块
    const userData = await registerApi({
      username: value.username,
      password: value.password,
      phone: value.phone,
    });
    
    // 如果到这里说明注册成功
    ElNotification({
      message: '注册成功！请登录',
      title: '注册成功',
      type: 'success',
    });
    
    // 注册成功后跳转到登录页
    await router.push('/auth/login');
  } catch (error: any) {
    console.error('Register error:', error);
    
    // 从错误响应中提取错误信息
    const errorMessage = error?.response?.data?.message || 
                        error?.message || 
                        '注册失败，请稍后重试';
    
    ElNotification({
      message: errorMessage,
      title: '注册失败',
      type: 'error',
    });
  } finally {
    loading.value = false;
  }
}
</script>

<template>
  <AuthenticationRegister
    :form-schema="formSchema"
    :loading="loading"
    @submit="handleSubmit"
  />
</template>
